<!-- menu -->
<template>
  <div>
    <div class="menu content_box">
      <div class="header_row flex align-center flex-wrap" v-if="hasBtn('menuManage:query')">
        <div class="flex align-center m-r-2">
          <span class="tit_span nowarp">搜素：</span>
          <el-input v-model="searchObj.MenuName" clearable placeholder="输入菜单名称"></el-input>
        </div>

        <el-button type="primary" @click="handleFilter">查询</el-button>
      </div>
      <div class="m-b-1 neck_box flex align-center space-between">
        <el-button type="success" @click="addMenu" v-if="hasBtn('menuManage:add') && searchObj.PlatFormType == 'PC' ">新增菜单</el-button>
        <el-button type="success" @click="addAppMenus = true, appTitle = '新增', searchObj = {PlatFormType:'APP'}" v-if="hasBtn('menuManage:add') && searchObj.PlatFormType == 'APP' ">新增菜单</el-button>

        <!--        <el-pagination-->
        <!--          background-->
        <!--          @current-change="handleCurrentChange"-->
        <!--          :current-page="searchObj.currentPage"-->
        <!--          :page-size="10"-->
        <!--          layout="total, prev, pager, next, jumper"-->
        <!--          :total="pageTotal"-->
        <!--        >-->
        <!--        </el-pagination>-->

      </div>

      <el-tabs type="border-card" @tab-click="handleClick" v-loading="listLoading" v-model="searchObj.PlatFormType">
        <el-tab-pane label="电脑端" name="PC">
          <el-table ref="menuTable" row-key="Id" :tree-props="{ children: 'ChildList', hasChildren: 'hasChildren' }" :indent="48" :data="list" border fit highlight-current-row :max-height="tableHeight">
            <el-table-column label="菜单名称" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.MenuName }}
              </template>
            </el-table-column>
            <el-table-column label="菜单排序" align="center" width="80">
              <template slot-scope="scope">
                {{ scope.row.MenuSort }}
              </template>
            </el-table-column>
            <el-table-column label="菜单图标" align="center" width="180" show-overflow-tooltip>
              <template v-if="scope.row.PlatFormType == 'PC'" slot-scope="scope">
                <!-- <i :class="scope.row.MenuIcon"></i> -->
                <template v-if="calcicon(scope.row.MenuIcon)">
                  <i :class="scope.row.MenuIcon" />
                </template>
                <template v-else>
                  <svg-icon :icon-class="scope.row.MenuIcon" />
                </template>
                {{ scope.row.MenuIcon }}
              </template>
            </el-table-column>
            <el-table-column label="菜单链接" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.MenuPath }}
              </template>
            </el-table-column>

            <el-table-column label="菜单备注" align="center" width="120" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ scope.row.Remark }}
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" v-if="
              hasBtn('menuManage:edit') ||
              hasBtn('menuManage:addson') ||
              hasBtn('menuManage:delete')
            ">
              <template slot-scope="scope">
                <el-button size="small" @click="gotoEdit(scope.row)" v-if="hasBtn('menuManage:edit')">编辑</el-button>
                <el-button size="small" @click="addChildMenu(scope.row)" v-if="hasBtn('menuManage:addson')">添加子菜单</el-button>
                <el-button size="small" @click="del(scope.row.Id)" v-if="hasBtn('menuManage:delete')">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <el-tab-pane label="移动端" name="APP">
          <el-table ref="menuTable" :indent="48" :data="list" border fit highlight-current-row :max-height="tableHeight">
            <el-table-column type="expand">
              <template slot-scope="props">
                <div class="flex" style="padding: 0 0 10px 0">
                  <div class="amount">
                    <span>每行图标数量 : </span>
                    <el-radio disabled v-model="props.row.MenuPath" label=4>4</el-radio>
                    <el-radio disabled v-model="props.row.MenuPath" label=5>5</el-radio>
                  </div>
                  <el-button type="success" :disabled="props.row.MenuName == '底部导航'" @click="addList(props.row)" v-if="hasBtn('menuManage:add') && searchObj.PlatFormType == 'APP' ">新增图标</el-button>
                </div>

                <div class="flex">

                  <div class="app-show app-border">
                    <div class="show-box">
                      <div v-for="item of props.row.ChildList" :key="item.MenuSort" class="showlist" :class="props.row.MenuPath == 5 ? 'listWidth' : ''">
                        <div class="showimg showimg-border">
                          <img width="100%" height="100%" :src="item.MenuIcon" alt="">
                        </div>
                        <div class="showTitle">{{item.MenuName}}</div>
                      </div>
                    </div>
                  </div>

                  <div class="app-edit app-border">

                    <div class="flex flex-warp">
                      <div v-for="item of props.row.ChildList" :key="item.MenuSort" class="list flex">
                        <div>
                          <div>
                            <span>标题:</span>
                            <el-input :disabled="!item.MenuType" class="title-put" v-model="item.MenuName" placeholder="请输入内容"></el-input>
                          </div>
                          <div>
                            <span>路径:</span>
                            <el-input :disabled="!item.MenuType" class="title-put" v-model="item.MenuPath" placeholder="请输入内容"></el-input>
                          </div>
                          <div>
                            <span>排序:</span>
                            <el-input type="number" :disabled="!item.MenuType" class="title-put" v-model="item.MenuSort" placeholder="请输入内容"></el-input>
                          </div>
                          <div>
                            <span>备注:</span>
                            <el-input :disabled="!item.MenuType" class="title-put" v-model="item.Remark" placeholder="请输入内容"></el-input>
                          </div>
                        </div>
                        <div class="img">
                          <img width="100%" height="100%" v-if="!item.MenuType" :src="item.MenuIcon" alt="">
                          <el-upload :disabled="!item.MenuType" :action="upload" :headers="headerObj" list-type="picture-card" :on-preview="handlePictureCardPreview" :auto-upload="true" :on-remove="handleRemove" :on-success="upLoadSuccess" :limit=1>
                            <i class="el-icon-plus"></i>
                          </el-upload>
                          <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                          </el-dialog>
                        </div>
                        <div class="edit">
                          <div>
                            <el-button :disabled="props.row.MenuName == '底部导航'" v-if="!item.MenuType" type="primary" @click="editList(item)">编辑</el-button>
                            <el-button v-else type="primary" @click="appSave(props.row, item)">保存</el-button>
                          </div>
                          <div>
                            <el-button :disabled="props.row.MenuName == '底部导航'" v-if="!item.MenuType" type="danger" @click="deleList(item.Id)">删除</el-button>
                            <el-button v-else type="danger" @click="item.MenuType = false, getList()">取消</el-button>
                          </div>
                        </div>
                      </div>

                    </div>

                  </div>
                </div>

              </template>
            </el-table-column>
            <el-table-column label="菜单名称" align="center" prop="MenuName" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="菜单排序" align="center" prop="MenuSort" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="菜单备注" align="center" prop="Remark" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="编辑" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-button size="small" :disabled="scope.row.MenuName == '底部导航'" @click="editBar(scope.row),appTitle = '编辑'">编辑</el-button>
                <el-button size="small" :disabled="scope.row.MenuName == '底部导航'" @click="deleBar(scope.row.Id)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog :title="appTitle" :visible.sync="addAppMenus" width="60%">
        <div>
          <!-- <div class="flex">
            <div class="app-menu">
              <span>菜单名称:</span>
            </div>
            <div>
              <el-input  class="title-put diawidth" v-model="searchObj.appMenuName" placeholder="请输入菜单名称"></el-input>
            </div>
          </div>
          <div class="flex">
            <div class="app-menu">
              <span>菜单排序:</span>
            </div>
            <div>
              <el-input min=1 type="number" class="title-put diawidth" v-model="searchObj.MenuSort" placeholder="请输入菜单排序"></el-input>
            </div>
          </div>
          <div class="flex">
            <div class="app-menu">
              <span>菜单备注:</span>
            </div>
            <div>
              <el-input min=1 class="title-put diawidth" v-model="searchObj.Remark" placeholder="请输入菜单备注"></el-input>
            </div>
          </div>
          <div class="flex">
            <div class="app-menu">
              <span>每行图标数量 : </span>
            </div>
            <div class="app-radio">
              <el-radio  v-model="searchObj.MenuPath" label='1'>4</el-radio>
              <el-radio v-model="searchObj.MenuPath" label='2'>5</el-radio>
            </div>
          </div> -->
          <el-form label-width="150px" :rules="rules" :model="searchObj" ref="form" class="menuBox">
            <el-form-item label="菜单名称" prop="MenuName">
              <el-input v-model="searchObj.MenuName" placeholder="请输入菜单名称"></el-input>
            </el-form-item>
            <el-form-item label="菜单排序" prop="MenuSort">
              <el-input type="number" v-model="searchObj.MenuSort" placeholder="请输入菜单排序"></el-input>
            </el-form-item>
            <el-form-item label="菜单备注" prop="Remark">
              <el-input v-model="searchObj.Remark" placeholder="请输入菜单备注"></el-input>
            </el-form-item>
            <el-form-item label="请选择每行图标数量" prop="MenuPath">
              <el-radio v-model="searchObj.MenuPath" label=4>4</el-radio>
              <el-radio v-model="searchObj.MenuPath" label=5>5</el-radio>
            </el-form-item>
          </el-form>

        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addAppMenus = false">取 消</el-button>
          <el-button type="primary" @click="addAppMenu()">确 定</el-button>
        </span>
      </el-dialog>

    </div>
    <MenuForm :show.sync="addMenuVisible" :form-data="menuObj" :isAddChild="isAddChild" :form-name="dialogTableTitle" :PlatFormType="searchObj.PlatFormType" @finish="getList"></MenuForm>
  </div>
</template>

<script>
  import { GetUploadToken } from '@/api/ShareSetting/poster'
  import { getList, deleteApi, save } from '@/api/system/menu'
  import MenuForm from './components/MenuForm'
  export default {
    //import引入的组件需要注入到对象中才能使用
    name: 'mymenu',
    components: { MenuForm },
    data() {
      //这里存放数据
      return {
        rules: {
          MenuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
          MenuSort: [{ required: true, message: '请输入菜单排序', trigger: 'blur' }],
          //   parent_id:[{ required: true, message: '请选择父级节点', trigger: 'change'}],
          MenuPath: [{ required: true, message: '请选择每行图标数量', trigger: 'blur' }],
        },
        addAppMenus: false,
        dialogImageUrl: '',
        dialogVisible: false,
        upload: process.env.VUE_APP_UPLOAD_API + '/api/Tools/UploadFiles',
        headerObj: {
          Authorization: ''
        },
        appObj: {},
        appTitle: '',
        editId: '',
        PlatFormType: "PC",
        addMenuVisible: false,
        dialogTableTitle: "新增菜单",
        isAdd: false,
        isAddChild: false,
        menuObj: {},
        list: [],
        total: 0,
        listLoading: true,
        searchObjTmpl: {},
        searchObj: {
          PlatFormType: 'PC',
          // PlatFormType: 'APP',
          MenuName: "",
          currentPage: 0,
          MenuPath: '',
          MenuType: true,//True：目录，False：菜单
          MenuSort: '',
          Remark: ''
        },
        listQuery: {
          IsPaging: false, //是否分页
          SortName: 'MenuSort',
          SortType: false
        },
        tableHeight: 0
      };
    },
    //监听属性 类似于data概念
    computed: {

    },
    //监控data中的数据变化
    watch: {
      'addAppMenus': {
        handler(newVal) {
          console.log(newVal)
          if (this.searchObj.PlatFormType == 'APP') {
            if (!newVal) {
              console.log('成功')
              this.$refs['form'].clearValidate()
              this.searchObj = { PlatFormType: 'APP' }
            }
          }
        },
        immediate: true
      }
    },
    created() {
      if (!this.headerObj.Authorization) {
        this.GetUploadTokenFun()
      }

      this.searchObjTmpl = this.$deepClone(this.searchObj)
      this.getList()
    },
    activated() { },
    deactivated() { },
    destroyed() {
      window.removeEventListener('resize', this.resize)
    },
    mounted() {
      this.$nextTick(() => {
        this.tableHeight = window.innerHeight - this.$refs.menuTable.$el.offsetTop - 150;
      })
      window.addEventListener('resize', this.resize)
      // window.onresize = () => {
      //   this.tableHeight = window.innerHeight - this.$refs.menuTable.$el.offsetTop - 150;
      // }
    },
    //方法集合
    methods: {
      cancel() {
        this.$refs['form'].clearValidate()
      },
      async editBar(item) {
        console.log(item)
        this.searchObj = item
        // this.searchObj.appMenuName = item.MenuName
        // this.searchObj.MenuSort = item.MenuSort
        // this.searchObj.Remark = item.Remark
        // this.searchObj.Id = item.Id
        // this.searchObj.MenuPath = item.MenuPath
        // this.searchObj.ChildList = item.ChildList
        this.addAppMenus = true
      },
      async deleBar(id) {
        console.log(id)
        this.$confirm('确认删除此条数据吗？').then(async () => {
          const { code } = await deleteApi({
            Id: id
          })
          if (code == 200) {
            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      },
      async addAppMenu() {
        if (!this.searchObj.MenuName) {
          this.$notify({
            title: '错误',
            message: '请填写菜单名称',
            type: 'error',
            duration: 3000
          })
          return
        }
        if (!this.searchObj.MenuSort) {
          this.$notify({
            title: '错误',
            message: '请填写菜单排序',
            type: 'error',
            duration: 3000
          })
          return
        }
        if (!this.searchObj.MenuPath) {
          this.$notify({
            title: '错误',
            message: '请选择每行图标数量',
            type: 'error',
            duration: 3000
          })
          return
        }
        if (this.appTitle == '新增') {

          this.appObj = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "MenuName": this.searchObj.MenuName,
            "MenuType": true, //True：目录，False：菜单
            "MenuPath": this.searchObj.MenuPath,
            "MenuSort": this.searchObj.MenuSort,//排序
            "PlatFormType": "APP",
            "Remark": this.searchObj.Remark, //备注
            "ChildList": []
          }
          const { code } = await save(this.appObj)
          if (code == 200) {
            this.$notify({
              title: '添加成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.searchObj = { PlatFormType: 'APP' }
            this.getList()
            this.addAppMenus = false
          }
        }
        if (this.appTitle == '编辑') {

          this.appObj = {
            "Id": this.searchObj.Id,
            "MenuName": this.searchObj.MenuName,
            "MenuPath": this.searchObj.MenuPath, //页面地址
            "MenuType": true, //True：目录，False：菜单
            "MenuSort": this.searchObj.MenuSort,//排序
            "PlatFormType": "APP",
            "Remark": this.searchObj.Remark, //备注
            "ChildList": this.searchObj.ChildList
          }
          const { code } = await save(this.appObj)
          if (code == 200) {
            this.$notify({
              title: '修改成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.searchObj = { PlatFormType: 'APP' }
            this.getList()
            this.addAppMenus = false
          }
        }

      },
      async appSave(MenuParentId, item) {
        console.log(MenuParentId)
        const obj = {
          "MenuName": item.MenuName, //页面名称
          "MenuPath": item.MenuPath, //页面地址
          "MenuParentId": MenuParentId.Id, //上级菜单Id
          "MenuIcon": item.MenuIcon, //菜单图标
          "MenuType": false, //True：目录，False：菜单
          "MenuSort": item.MenuSort, //排序
          "PlatFormType": "APP", //平台类型
          "Remark": item.Remark //备注
        }
        if (item.Id != "00000000-0000-0000-0000-000000000000") {
          obj.Id = item.Id
        }
        await save(obj).then((res) => {
          this.$notify({
            title: '修改成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
        // let addObj = this.$deepClone(this.addObj)
      },
      addList(item) {
        console.log(item)
        this.searchObj = { PlatFormType: "APP" }
        this.appObj = {
          "Id": "00000000-0000-0000-0000-000000000000",
          "MenuName": this.searchObj.MenuName, //名称
          "MenuPath": this.searchObj.MenuPath, //路径
          "MenuType": false, //True：目录，False：菜单
          "MenuSort": this.searchObj.MenuSort, //排序
          "PlatFormType": "APP",
          "Remark": this.searchObj.Remark
        }
        item.ChildList.push(this.appObj)
        console.log(item)
        this.appObj = {}
      },
      async deleList(id) {
        this.$confirm('确认删除此条数据吗？').then(async () => {
          if (id == "00000000-0000-0000-0000-000000000000") {
            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.getList()
            return
          }
          const { code } = await deleteApi({
            Id: id
          })
          if (code == 200) {
            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })

      },
      editList(item) {
        console.log(item)
        for (let item of this.list) {
          for (let res of item.ChildList) {
            res.MenuType = false
          }
        }
        item.MenuType = true
      },

      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      upLoadSuccess(res) {
        console.log('上传结束', res)
        for (let item of this.list) {
          for (let ite of item.ChildList) {
            if (ite.MenuType) {
              ite.MenuIcon = res.data.fileUrl
              console.log(ite)
            }
          }



        }
        //  else {
        //   if (this.sstimer) {
        //     clearTimeout(this.sstimer)
        //   }
        //   this.sstimer = setTimeout(() => {
        //     this.$notify({
        //       title: '上传失败',
        //       message: res.msg,
        //       type: 'warning',
        //       duration: 4500
        //     })
        //   }, 800)
        // }
        // }
      },
      async GetUploadTokenFun() {
        let { Data } = await GetUploadToken()
        this.headerObj.Authorization = Data || ''
      },





      resize() {
        this.tableHeight = window.innerHeight - this.$refs.menuTable.$el.offsetTop - 150;
      },
      calcicon(icon) {
        if (icon.includes('el-icon')) {
          return true
        }
        return false
      },
      addMenu() {
        this.isAdd = true
        this.isAddChild = false
        this.addMenuVisible = true
        this.menuObj = {
          PlatFormType: this.searchObj.PlatFormType
        }
        this.dialogTableTitle = '新增菜单'
      },
      gotoEdit(obj) {

        this.isAdd = false
        this.isAddChild = false
        console.log(obj)
        this.menuObj = obj
        this.addMenuVisible = true
        this.dialogTableTitle = '编辑菜单'
      },
      addChildMenu(obj) {
        console.log(obj)

        this.isAdd = true
        this.isAddChild = true

        this.menuObj = this.$deepClone({ ...obj, 'MenuParentName': obj.MenuName, 'MenuParentId': obj.Id })
        this.addMenuVisible = true
        this.dialogTableTitle = '新增子菜单'
      },

      handleCurrentChange() { },
      handleClick(a, b) {
        this.handleFilter()
      },
      resetFilter() {
        this.searchObj = this.$deepClone(this.searchObjTmpl)
        this.handleFilter()
      },
      sortChange(data) {
        const { prop, order } = data
        this.listQuery.SortName = prop
        if (order === 'ascending') {
          this.listQuery.SortType = true
        } else {
          this.listQuery.SortType = false
        }
        this.handleFilter()
      },
      handleFilter() {
        // this.listQuery.PageIndex = 1
        this.getList()
      },
      getQuery() {
        const params = {
          ...this.searchObj,
          ...this.listQuery,
        }
        for (let i in params) {
          if (params[i] === '') {
            delete params[i]
          }
        }
        return params
      },
      async getList() {
        this.listLoading = true
        const params = this.getQuery()
        // params.UserId = this.userId
        // params.ExtendId = this.userId
        const { Data, Total } = await getList(params)
        this.listLoading = false
        let that = this
        function loop(arr) {
          for (let item of arr) {
            if (item.ChildList.length > 0) {
              item.ChildList = that.newdataList(item.ChildList)
              loop(item.ChildList)
            }
          }

        }
        let lst = this.newdataList(Data)
        loop(lst)
        this.list = lst || []
        this.total = Total || 0
        for (let res of this.list) {
          if (!res.Remark) {
            res.Remark = '-'
          }
        }

        console.log(this.list)
        console.log(this.searchObj.PlatFormType)


        // console.log(list)
      },
      async del(id) {
        this.$confirm('确认删除此条数据吗？').then(async () => {
          const { code } = await deleteApi({
            Id: id
          })
          if (code == 200) {
            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })

      },
      newdataList: function (arr) {
        return this.sortKey(arr, "MenuSort");
      },
      sortKey(array, key) {
        return array.sort(function (a, b) {
          var x = a[key];
          var y = b[key];
          return x < y ? -1 : x > y ? 1 : 0;
        });
      },
    }
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .app-border {
    border: 1px solid #d3dce6;
  }
  .app-show {
    min-width: 400px;
    width: 30%;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
    overflow-y: scroll;
    overflow: hidden;
  }
  .app-edit {
    padding: 15px 0 0 15px;
    margin-left: 10px;
    width: 70%;
    height: 500px;
    overflow: hidden;
    overflow-y: scroll;
    min-width: 640px;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .bg-purple {
    border: 1px solid #d3dce6;
    margin-bottom: 10px;
    width: 100%;
    height: 80px;
    margin-left: 5%;
  }
  .showlist {
    width: 25%;
    margin-top: 10px;
    text-align: center;
  }
  .listWidth {
    width: 20%;
  }
  .list {
    width: 570px;
    height: 200px;
    padding: 15px 0 0 15px;
    margin: 10px;
    border-radius: 20px;
    border: 1px solid #d3dce6;
  }
  .show-box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    height: 100px;
  }
  .showimg {
    width: 70px;
    height: 70px;
    border: 1px solid #d3dce6;
    border-radius: 50%;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    margin-bottom: 5px;
    overflow: hidden;
  }
  .showimg-border {
    border: 0;
    border-radius: 0;
  }
  .title-put {
    width: 200px;
    margin: 0 30px 5px 10px;
  }
  .diawidth {
    width: 120%;
  }
  .edit {
    margin: 20px 0 0 40px;
  }
  .edit :first-child {
    margin-bottom: 20px;
  }
  .flex-warp {
    flex-wrap: wrap;
  }
  .img {
    margin-top: 10px;
    width: 150px;
    height: 150px;
    overflow: hidden;
  }
  .amount {
    line-height: 40px;
    margin: 0 20px 0 0;
  }
  .app-menu {
    width: 15%;
    text-align: right;
    line-height: 45px;
    margin-bottom: 5px;
  }
  .app-radio {
    line-height: 45px;
    margin-left: 10px;
  }
</style>
